import { Button, Card, Form, Input, Table } from "antd";
import { useEffect, useState } from "react";
import { getTableApi, getToken } from "../utils/client";
import { v4 as uuidv4 } from "uuid";
import type { ColumnType } from 'antd/es/table';

export interface RecordListProps {
    curClientId: string;
    curDatabase: string;
    curTable: string;
}

type Row = string[];

const PAGE_SIZE = 20;

function RecordList(props: RecordListProps) {
    const [tmpWhere, setTmpWhere] = useState("");
    const [where, setWhere] = useState("");
    const [columnList, setColumnList] = useState<string[]>([]);
    const [rowList, setRowList] = useState<Row[]>([]);
    const [curPage, setCurPage] = useState(0);
    const [totalCount, setTotalCount] = useState(0);


    const loadRecordList = async () => {
        setColumnList([]);
        setRowList([]);
        setTotalCount(0);
        const client = getTableApi();
        const res = await client.tableQueryPost({
            tableQueryPostRequest: {
                id: props.curClientId,
                token: getToken(),
                db: props.curDatabase,
                table: props.curTable,
                where: where,
                offset: curPage * PAGE_SIZE,
                limit: PAGE_SIZE,
            },
        });
        console.log("1111", res);
        if (res.columns !== undefined) {
            setColumnList(res.columns.map(item => item.name ?? ""));
        }
        if (res.values !== undefined) {
            const tmpRowList = [] as Row[];
            for (const row of res.values) {
                const tmpList = row.slice();
                tmpList.push(uuidv4());
                tmpRowList.push(tmpList);
            }
            setRowList(tmpRowList);
        }
        setTotalCount(res.count ?? 0);
    };

    const calcCloumnsType = () => {
        return columnList.map((column, index) => ({
            title: column,
            dataIndex: index,
        } as ColumnType<Row>))
    };

    useEffect(() => {
        if (props.curClientId !== "" && props.curDatabase !== "" && props.curTable !== "") {
            if (curPage == 0 && where == "") {
                loadRecordList();
            } else {
                setCurPage(0);
                setWhere("");
            }
            setTmpWhere("");
        } else {
            setColumnList([]);
            setRowList([]);
            setTotalCount(0);
        }
    }, [props.curClientId, props.curDatabase, props.curTable]);

    useEffect(() => {
        loadRecordList();
    }, [where, curPage]);

    return (
        <Card style={{ border: "none" }}
            bodyStyle={{ height: "calc(100vh - 130px)", overflowY: "auto" }}
            extra={
                <Form layout="inline">
                    <Form.Item label="WHERE" >
                        <Input style={{ width: "calc(100vw - 700px)" }} value={tmpWhere} onChange={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            setTmpWhere(e.target.value);
                        }} />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            setWhere(tmpWhere);
                        }}>查询</Button>
                    </Form.Item>
                </Form>
            }>
            {columnList.length > 0 && (
                <Table rowKey={columnList[0]} columns={calcCloumnsType()} dataSource={rowList}
                    pagination={{
                        total: totalCount, pageSize: PAGE_SIZE, current: curPage + 1, onChange: page => setCurPage(page - 1),
                        showSizeChanger: false, hideOnSinglePage: true
                    }} />
            )}
        </Card>
    );
}

export default RecordList;